//重新验证刷新token有如下优点：
//1. 可以有效避免恶意的频繁请求
//2. 避免重复登陆，提升用户体验
const {Token} = require('../mongodb/models')
const jwt = require('jsonwebtoken')
const config = require('../config')
//免授权路径
const unlessPaths = [
	/^\/login/,
	/^\/test/,
	/^\/apiList.*/,
	/^\/projectInfo.*/,
	/^\/catalogList.*/,
	/^\/globalCodeList.*/
]

module.exports = async (ctx, next) => {
	for(let path of unlessPaths){
		if(path.test(ctx.url)){
			return next()
		}
	}
	if(ctx.header && ctx.header.authorization){
		const token = ctx.header.authorization.split(' ')[1]
		const dbToken = await Token.findOne({value: token})
		//token是否存在
		if(dbToken){
			const now = new Date().getTime()
			//token未过期，则验证token
			if(now-dbToken.createTime.getTime() < dbToken.expire){
				try{
					//jwt.verify方法验证token是否有效
					jwt.verify(token, config.secret)
				}catch(err){
					//token过期，但数据库中的token未过期销毁，则刷新token
					const user = jwt.decode(token)
					const newToken = jwt.sign({
						_id: user._id,
						adminAuth: user.adminAuth,
						email: user.email
					}, config.secret, {expiresIn: config.tokenExpires})
					await Token.updateOne({value: token}, {value: newToken})
					ctx.res.setHeader('Authorization', newToken)
				}
				return next()
			}else{
				console.log('token已过期：', token)
				//token过期，则清除该token
				Token.deleteOne({value: token})
			}
		}
	}
	ctx.status = 401
	ctx.body = 'Protected resource, use Authorization header to get access\n'
}